package vip.kqsy.cloud.blog.server.aspect;

import com.baidu.aip.contentcensor.AipContentCensor;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import vip.kqsy.cloud.core.common.exception.BizException;
import vip.kqsy.cloud.core.common.util.SpELParserUtil;

import java.lang.reflect.Method;
import java.util.Objects;

@Component
@Aspect
@RequiredArgsConstructor
public class AipAspect {

    private final AipContentCensor aipContentCensor;

    @Before("@annotation(vip.kqsy.cloud.blog.server.aspect.Aip)")
    public void before(JoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Object[] args = joinPoint.getArgs();
        Aip aip = method.getAnnotation(Aip.class);
        String text = SpELParserUtil.parse(method, args, aip.value(), String.class);

        JSONObject jsonObject = aipContentCensor.textCensorUserDefined(text);
        if (Objects.isNull(jsonObject) || jsonObject.getInt("conclusionType") != 1) {
            throw new BizException("内容包含有敏感信息");
        }
    }

}
